--------------------------------------------------------------------------------
-- Entity: Compteur16
--------------------------------------------------------------------------------
-- Copyright ... 2010
-- Filename          : Compteur16.vhd
-- Creation date     : 2010-04-14
-- Author(s)         : salim
-- Version           : 1.00
-- Description       : This module deals with asynchronism between RxUnit an TxUnit
--------------------------------------------------------------------------------
-- File History:
-- Date         Version  Author   Comment
-- 2010-04-14   1.00     salim     Creation of File
--------------------------------------------------------------------------------
library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

entity Compteur16 is 
	port  (
		clk : in std_logic;        -- input clock, 155 KHz.
		reset : in std_logic;
		rxd : in std_logic;
		tmpclk, tmprxd : out std_logic
	);
end Compteur16;

architecture arch of Compteur16 is

type state is (attente, compte);

begin
--------------------------------------------------------------------------------
-- Every 16 rising edges of clk:
-- * tmpclk <= '1'
-- * tmprxd recieves rxd at the 8th rising edge of clk
--------------------------------------------------------------------------------
	--tmpclk <= '0';
	process(clk, reset)
		variable cpt : integer range 0 to 15 := 0;
		variable cpt2: integer range 0 to 10 := 0;
		variable myState : state := attente;
		begin
	if (reset = '0') then
		tmpclk <= '0';
		tmprxd <= '0';
		cpt := 0;
		cpt2:= 0;
		myState := attente;
	elsif (clk = '1' and clk'event) then
		case myState is
		when attente =>
			if (rxd = '0') then
				cpt := (cpt + 1) mod 8;
				if (cpt = 0) then -- 8 tops d'horloges ont été comptabilisés						
					tmpclk <= '1';
					-- increment the second counter to know when to stop counting
					cpt2 := (cpt2 + 1) mod 11;
					-- transmit data
					tmprxd <= rxd;
					-- move to next state
					myState := compte;
				else
					tmpclk <= '0';
				end if;
			end if;
		-- etat compte
		when compte =>
			-- comptage de 16 en 16
			cpt := (cpt + 1) mod 16;
			if (cpt = 0) then -- 16 tops d'horloges ont été comptabilisés
				tmpclk <= '1';
				-- increment the second counter
				cpt2 := (cpt2 + 1) mod 11;
				-- transmit data
				tmprxd <= rxd;
			else
				tmpclk <= '0';
			end if;
			if (cpt2 = 0) then
			-- on a fini de recevoir tous les bits
			-- start, data, parite et stop
			-- on rebascule en attente de la prochaine transmission
			myState := attente;
			end if;
		end case;
	end if;
	end process;
end arch;
